package com.spark.data

import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v7.widget.GridLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.spark.common.BaseFragment
import com.spark.common.ext.alert
import kotlinx.android.synthetic.main.frag_data_retrieval.*

/**
 * 资料检索
 */
class MaterialRetrievalFragment : BaseFragment() {
    companion object {
        fun newInstance(): MaterialRetrievalFragment {
            val fragment = MaterialRetrievalFragment()
            val args = Bundle()

            fragment.arguments = args
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_data_retrieval
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        iv_back.setOnClickListener { activity?.apply { pop() } }

        val retrievalHistoryAdapter = RetrievalHistoryAdapter(R.layout.item_retrieval_history)
        recy_search_history.adapter = retrievalHistoryAdapter
        recy_search_history.layoutManager = object : GridLayoutManager(activity, 5) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        retrievalHistoryAdapter.addData(mutableListOf("安全生产手册", "考核准则", "任务", "安全", "通报"))

        iv_back.setOnClickListener { }
        tv_borrow_list.setOnClickListener {
            activity?.apply { start(BorrowListFragment.newInstance()) }
        }

        iv_del.setOnClickListener {
            retrievalHistoryAdapter.data.clear()
            retrievalHistoryAdapter.notifyDataSetChanged()
        }

        tv_search.setOnClickListener {
            val keyword = et_search.text.toString().trim()
            if (keyword.isNullOrBlank()) {
                alert("请输入关键词后再检索")
            } else {
                activity?.apply { start(DataQueryResultFragment.newInstance(keyword)) }
            }
        }
    }
}

class RetrievalHistoryAdapter(@LayoutRes layoutRes: Int) : BaseQuickAdapter<String, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: String?) {
        helper?.apply {
            if (item == null) return
            setText(R.id.tv_retrieval_tag, item)
        }
    }

}
